#!/usr/bin/env ruby

require 'net/https'
require 'uri'

module RubygemsAPI
  extend self

  def published?(name, version)
    uri = URI.parse("https://rubygems.org/api/v2/rubygems/#{name}/versions/#{version}.json")
    Net::HTTP.get_response(uri).is_a?(Net::HTTPSuccess)
  end
end

module Git
  extend self

  def tag_and_push(version)
    if tag_exists?(version)
      yield
    else
      tag(version) && yield && push_tags
    end
  end

  def tag_exists?(version)
    system('git', 'rev-parse', '--verify', "v#{version}^{commit}", out: File::NULL, err: File::NULL)
  end

  def tag(version)
    puts "Running: git tag -m 'Version #{version}' v#{version}"
    system('git', 'tag', '-m', "Version #{version}", "v#{version}")
  end

  def delete_tag(version)
    puts "Running: git tag -d v#{version}"
    system('git', 'tag', '-d', "v#{version}")
  end

  def push_tags
    puts "Running: git push --tags"
    system('git', 'push', '--tag')
  end
end

spec_path, *release_command = ARGV
release_command = %w(bundle exec rake release) if release_command.empty?

spec = Gem::Specification.load(spec_path)
if RubygemsAPI.published?(spec.name, spec.version)
  puts "#{spec.name} version #{spec.version} is already published."
  exit 0
elsif !spec.metadata['allowed_push_host']
  puts "Can't release the gem: spec.metadata['allowed_push_host'] must be defined."
  exit 1
else
  is_successful = Git.tag_and_push(spec.version) do
    system(*release_command)
  end
  is_successful ? exit(0) : exit(1)
end
